package com.stork.sms.activity;
import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ExpandableListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.navdrawer.SimpleSideDrawer;
import com.stork.sms.R;
import com.stork.sms.adapter.ExpandableAdapter;
import com.stork.sms.service.all.ServiceMethods;
import com.stork.sms.service.fees.Fees;
import com.stork.sms.service.fees.FeesAmount;
import com.stork.sms.service.fees.TermFees;
import com.stork.sms.utilities.Constants;
import com.stork.sms.utilities.SharedPreference;


public class FeesActivity extends Activity {
	private ArrayList<TermFees> termfees;
	private static final String SOAP_ACTION = "http://tempuri.org/getfees";
	private static final String METHOD_NAME = "getfees";
	private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "http://10.0.2.2:2341/smsservice/webmethods.asmx";
    public static final String LOGIN_ID="username";
    private SimpleSideDrawer ssdrawer;
    Fees fees;
    FeesAmount feesAmount;
    ProgressDialog progressdialog;
    final ArrayList<String> todoItems = new ArrayList<String>(); 
    TextView date;
    TextView rno,aperyear,tamt;
    private ExpandableListView expandableFeesListView;
    private ExpandableAdapter FeesAdapter;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_fees_mgnt_service);
		ActionBar actionBar = getActionBar();
		actionBar.setTitle("Fees Management");
		actionBar.setDisplayHomeAsUpEnabled(true);
		ssdrawer=new SimpleSideDrawer(this);
		ssdrawer.setRightBehindContentView(R.layout.drawer);
		Resources res = this.getResources();
	    Drawable devider = res.getDrawable(R.drawable.line);
		expandableFeesListView=(ExpandableListView)findViewById(R.id.expandableListView1);
		expandableFeesListView.setGroupIndicator(null);
		   expandableFeesListView.setDivider(devider);
		   expandableFeesListView.setChildDivider(devider);
		   expandableFeesListView.setDividerHeight(1);
		   registerForContextMenu(expandableFeesListView);
//		date=(TextView)findViewById(R.id.date);
//		   date.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
				new serviceCall().execute();
//			}
//		});
		   
		   expandableFeesListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
			int previousItem=-1;
			@Override
			public void onGroupExpand(int groupPosition) {
				// TODO Auto-generated method stub
				 if (groupPosition != previousItem){
					 expandableFeesListView.collapseGroup(previousItem);
	                    previousItem = groupPosition;
	                }
	                else{
	                	expandableFeesListView.collapseGroup(groupPosition);
	                    previousItem = -1;
	                }
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
	      switch (item.getItemId()) {
	         // Respond to the action bar's Up/Home button
	         case android.R.id.home:
	        	 super.onBackPressed();
	         return true;
	         case R.id.action_settings:
	 			ssdrawer.toggleRightDrawer();
	 			return true;
	 		
	      }
	      return super.onOptionsItemSelected(item);
	   }
	class serviceCall extends AsyncTask<String, String,Fees>
	{	
		Constants con;
		Toast toast = Toast.makeText(getApplicationContext(), "",
	            Toast.LENGTH_SHORT);
		
		protected void onPostExecute(Fees result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if(progressdialog.isShowing())
				progressdialog.dismiss();
			
			String code=fees.getCode();
			String msg=fees.getMessage();
			System.out.println("fees value code is"+code);
			System.out.println("fees value message is"+msg);
			System.out.println("fees size"+fees.getFeesAmount().getTermfees().size());
			String codeval=fees.getCode();
			if(codeval.equalsIgnoreCase("111")){
		          for(int j=0;j<fees.getFeesAmount().getTermfees().size();j++){
		          todoItems.add(fees.getFeesAmount().getTermfees().get(j).getPaymentname());}
			}
			System.out.println("resultttttttttttttttttttt"+todoItems);
			if(code.equalsIgnoreCase(con.mSERVICEINVALID)){
//				Log.i("inside post","444 exception");
				
				FeesActivity.this.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						 final AlertDialog.Builder alertBox = new AlertDialog.Builder(FeesActivity.this);
						// TODO Auto-generated method stub
						String msg=fees.getMessage();
						
						toast.setText(msg);
						toast.show();
						toast.setText(msg);
						toast.show();
						alertBox.setTitle("Error Message");
						alertBox.setMessage(msg);
						alertBox.setCancelable(true);
						alertBox.setPositiveButton("Yes",
			                    new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int id) {
			                    Intent A=new Intent(FeesActivity.this,GridHomeMenuActivity.class);
			                    startActivity(A);
			                    finish();
			                    }
			                	
			            });
						AlertDialog ad=alertBox.create();
						ad.show();	
					}
					});
			}
			else if(code.equalsIgnoreCase(con.mSERVICEFAILED)){
//				Log.i("inside post","404 exception");
				
FeesActivity.this.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						 final AlertDialog.Builder alertBox = new AlertDialog.Builder(FeesActivity.this);
						// TODO Auto-generated method stub
						String msg=fees.getMessage();
						
						toast.setText(msg);
						toast.show();
						toast.setText(msg);
						toast.show();
						alertBox.setTitle("Error Message");
						alertBox.setMessage(msg);
						alertBox.setCancelable(true);
						alertBox.setPositiveButton("Yes",
			                    new DialogInterface.OnClickListener() {
			                public void onClick(DialogInterface dialog, int id) {
			                    Intent A=new Intent(FeesActivity.this,GridHomeMenuActivity.class);
			                    startActivity(A);
			                    finish();
			                    }
			                	
			            });
						AlertDialog ad=alertBox.create();
						ad.show();	
					}
					});

			}else{
			FeesAdapter=new ExpandableAdapter(FeesActivity.this, result.getFeesAmount().getTermfees());
			expandableFeesListView.setAdapter(FeesAdapter);
			}
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progressdialog=new ProgressDialog(FeesActivity.this);
			progressdialog.setMessage("Please Wait......");
			progressdialog.setCancelable(false);
			progressdialog.show();
		}

		@Override
		protected Fees doInBackground(String... params) {
				String username=SharedPreference.readString(getApplicationContext(), LOGIN_ID, "");
				ServiceMethods sm=new ServiceMethods();
				fees=sm.getfeesdetails(username);
				return fees;
		}
	}


	/*public void Call()
    {
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        String w="DAV012K14LKG1";
        
   	 PropertyInfo properties=new PropertyInfo();
   		properties.name="studentid";
    	properties.type=PropertyInfo.STRING_CLASS;
    	
    	request.addProperty(properties,w);
       SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;

        envelope.setOutputSoapObject(request);

        HttpTransportSE httpTransport = new HttpTransportSE(URL);
        
        httpTransport.debug=true;
        
        try
        {
        	httpTransport.call(SOAP_ACTION, envelope);
            SoapPrimitive result=(SoapPrimitive) envelope.getResponse();
            Log.i("result", result.toString());
            
            System.out.println("resulttttttttttttttt"+result);
           String bracket =result.toString();
            GsonBuilder gsonBuilder=new GsonBuilder();
            Gson gson=gsonBuilder.create();
            fees=gson.fromJson(bracket, Fees.class);
          
//          System.out.println("fdate vaaaaaaaaaaaaaaaa"+f.getFeesAmount().getTermfees().get(0).getPaymentname());
//          System.out.println("fdate vaaaaaaaaaaaaaaaa"+baseresponse.getAttendance().getHalfdaylist().get(0).getDaylist());
//          System.out.println("fdate vaaaaaaaaaaaaaaaa"+baseresponse.getAttendance().getHalfdaylist().get(1).getDaylist());
          String codeval=fees.getCode();
          if(codeval.equalsIgnoreCase("111")){
          for(int j=0;j<=11;j++){
          todoItems.add(fees.getFeesAmount().getTermfees().get(j).getPaymentname());}
//          todoItems.add(pat.getAttendance().getHalfdaylist().get(0).getDaylist()); 
//          todoItems.add(pat.getAttendance().getHalfdaylist().get(1).getDaylist()); 
        }
          }
        catch (SocketException exception)
        {
            System.out.println(exception);
        } catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		}
    }*/

	

}
